/**
 * Edit window for ORM object
 */
Ext.define('app.crud.orm.ObjectWindow', {
	extend: 'Ext.window.Window',	
	objectName:null,
	dataGrid:null,
	indexGrid:null,
	indexStore:null,
	dataStore:null,
	configForm:null,
	tabPanel:null,
	objectList:null,
	
	 constructor: function(config) {			
			config = Ext.apply({
				modal: true,
		        layout:'fit',
		        width: app.checkWidth(700),
		        height:app.checkHeight(500),
		        closeAction: 'destroy',
		        tools:app.windowToolsElements()
		    }, config);		
			
		this.callParent(arguments);
	},
	
	initComponent:function(){
		
	  this.dataStore = Ext.create('Ext.data.Store', {
		   	model: 'app.crud.orm.Field',
		    proxy: {
		        type: 'ajax',
		    	url:app.crud.orm.Actions.listObjFields,
		        reader: {
		            type: 'json',
		            root: 'data',
		            idProperty: 'name'
		        },
		        extraParams:{'object':this.objectName},
		        actionMethods : {
		    		create : 'POST',
		    		read   : 'POST',
		    		update : 'POST',
		    		destroy: 'POST'
		    	},
		        simpleSortMode: false
		    }, 
		    autoLoad: false,
		    sorters: [{
					property:'system',
					direction:'DESC'
				},{
                    property : 'name',
                    direction: 'ASC'
			}]
	   });
	  
	  this.indexStore = Ext.create('Ext.data.Store', {
		   	model: 'app.crud.orm.Index',
		   	remoteSort:false,
		    proxy: {
		        type: 'ajax',
		    	url:app.crud.orm.Actions.listObjIndexes,
		    	reader:{
		    		type: 'json',
		            root: 'data',
		            idProperty: 'name'
		        },
		        extraParams:{'object':this.objectName},
		        actionMethods : {
		    		create : 'POST',
		    		read   : 'POST',
		    		update : 'POST',
		    		destroy: 'POST'
		    	},
		        simpleSortMode: true
		    }, 
		    autoLoad: false,
		    sorters: [{
                  property : 'name',
                  direction: 'ASC'
			}]
	   });

	   this.searchField = new SearchPanel({store:this.dataStore,fieldNames:['name' , 'title']});

	   var fieldsTbar = [];
	   
	   if(app.crud.orm.canEdit){
		   fieldsTbar.push(
		       {
		    	   text:appLang.ADD_FIELD,
		    	   scope:this,
		    	   handler:function(){
		    		   this.showEditField(0);
		    	   }
		       }
		   );
	   }
	   
	   fieldsTbar.push('->');
	   fieldsTbar.push(this.searchField);
	   
	   this.dataGrid = Ext.create('Ext.grid.Panel',{
				store: this.dataStore,
	            frame: false,
	            loadMask:true,
			    columnLines: true,
			    autoScroll:true,
			    bodyBorder:false,
				border:false,
			    title:appLang.FIELDS,
			    tbar:fieldsTbar,
			    defaults:{
			    	sortable:true
			    },
			    viewConfig:{
			    	stripeRows:true
			    },
			    forceFit:true,
			    columns: [{
			    			width:50,
			    			align:'center',
			    			dataIndex: 'name',
			    			colid:'editcolumn',
			    			renderer:function(value, metaData, record, rowIndex, colIndex, store){
			    				
			    				if(record.get('system')) {
									return '<img src="/i/system/locked.png" title="'+appLang.SYSTEM_PROTECTED_FIELD+'">';
							    }
								
			    				if(!record.get('system') && app.crud.orm.canEdit){
			    					return '<img src="/i/system/edit.png" title="'+appLang.EDIT_FIELD+'" style="cursor:pointer;">';
			    				}
			    				return '';
			    			}
			    		 },{
							text:appLang.TITLE,
							dataIndex:'title',
							align:'left',
							flex:1
				        },{
						    text: appLang.FIELD_NAME,
						    dataIndex: 'name',
						    width:120,
						    align:'left'
						 },{
							text:appLang.TYPE,
							dataIndex:'type',
							align:'center',
							width:80,
							colid:'link_type',
							scope:this,
							renderer:function(value, metaData, record, rowIndex, colIndex, store){
								if(record.get('link_type') == 'dictionary'){
									metaData.style = "background-color:#FFFDE4;cursor:pointer;";
								}
								return value;
							}
					     },{
			            	text:appLang.REQUIRED,
			            	dataIndex:'required',
			            	align:'center',
			            	width:60,
			            	renderer:app.checkboxRenderer
			             },{
			            	text:'NULL',
				            dataIndex:'db_isNull',
				            align:'center',
			            	width:60,
				            renderer:app.checkboxRenderer
			             },{
			            	text:appLang.UNIQUE,
				            dataIndex:'unique',
				            align:'center',
			            	width:60,
				            renderer:app.checkboxRenderer
				         },{
			            	text:appLang.IS_SEARCH,
				            dataIndex:'is_search',
				            align:'center',
			            	width:60,
				            renderer:app.checkboxRenderer
					     },{
				    			width:40,
				    			align:'center',
				    			dataIndex: 'name',
				    			colid:'deleteindex',
				    			renderer:function(value, metaData, record, rowIndex, colIndex, store){
				    				if(app.crud.orm.canDelete && !record.get('system')){
				    					return '<img src="/i/system/delete.gif" title="'+appLang.DELETE_FIELD+'" style="cursor:pointer;">';
				    				}
				    				return '';
				    			}
			             }
			    ]
		});

	   this.indexGrid = Ext.create('Ext.grid.Panel',{
			store: this.indexStore,
            frame: false,
            loadMask:true,
		    columnLines: true,
		    autoScroll:true,
		    bodyBorder:false,
			border:false,
		    title:appLang.INDEXES,
		    defaults:{
		    	sortable:true
		    },
		    viewConfig:{
		    	stripeRows:true
		    },
		    forceFit:true,
		    columns: [{
		    			width:40,
		    			align:'center',
		    			dataIndex: 'name',
		    			colid:'editcolumn',
		    			renderer:function(value, metaData, record, rowIndex, colIndex, store){
		    				
		    				if(record.get('primary')){
		    					return '<img src="/i/system/locked.png" title="'+appLang.SYSTEM_PROTECTED_INDEX+'">';
		    				}
		    				
		    				if(app.crud.orm.canEdit){
		    					return '<img src="/i/system/edit.png" title="'+appLang.EDIT_INDEX+'" style="cursor:pointer;">';
		    				}
		    				return '';
		    			}
		    		 },{
					    text: appLang.NAME,
					    dataIndex: 'name',
					    width:150,
					    flex:1,
					    align:'left'
					 },{
						text:appLang.FULLTEXT,
						dataIndex:'fulltext',
						align:'center',
						width:70,
						renderer:app.checkboxRenderer
		             },{
						text:appLang.UNIQUE,
						dataIndex:'unique',
						align:'center',
						width:70,
						renderer:app.checkboxRenderer
				     },{
		            	text:appLang.COLUMNS,
		            	dataIndex:'columns',
		            	align:'center',
		            	width:200
		             },{
			    			width:40,
			    			align:'center',
			    			dataIndex: 'name',
			    			colid:'deleteindex',
			    			renderer:function(value, metaData, record, rowIndex, colIndex, store){
			    				if(app.crud.orm.canDelete && !record.get('primary')){
			    					return '<img src="/i/system/delete.gif" title="'+appLang.EDIT_INDEX+'" style="cursor:pointer;">';
			    				}
			    				return '';
			    			}
		             }
		    ]
	   });
	   
	   
	   if(app.crud.orm.canEdit){
		   var mainConfButtons =[{
			   				  xtype:'button',
					    	  text:appLang.SAVE,
					    	  width:100,
					    	  listeners:{
					    		  click:{
					    			  fn:this.saveMainCfg,
					    			  scope:this
					    		  }
					    	  }			      
		   }];

		   this.dataGrid.on('itemdblclick',function(view , record , number , event , options){				  
				  if(record.get('system'))
					  return;			  
				  this.showEditField(record.get('name'));				  
			},this);
		   
		   
		   this.indexGrid.on('itemdblclick',function(view , record , number , event , options){				  
				  if(record.get('primary'))
					  return;			  
				  this.showEditIndex(record.get('name'));				  
			},this);
		      
		   this.indexGrid.addDocked({
			  dock:'top',
			  xtype:'toolbar',
			  items:[{
				  text:appLang.ADD_INDEX,
				  xtype:'button',
				  scope:this,
				  handler:function(){
					  this.showEditIndex(0);
				  }	  
			  }]
		   });
	   
	   }else{
		   var mainConfButtons = [];
	   }
	   
	   if(app.crud.orm.canEdit || app.crud.orm.canDelete){
		   this.indexGrid.on('cellclick',function(grid, cell, columnIndex, record , node , rowIndex , evt){
				  var column = grid.getHeaderCt().getHeaderAtIndex(columnIndex).colid;
				  
				  if(record.get('primary'))
					  return;
				  
				  switch(column){
				  
				  	case 'editcolumn' : 
					  	if(!app.crud.orm.canEdit){
				  			return;
				  		}
					  	this.showEditIndex(record.get('name'));	
				  		break;
				  	case 'deleteindex': 
				  		if(!app.crud.orm.canDelete){
				  			return;
				  		}
				  		this.deleteIndex(record.get('name'));
				  		break;
				  }
				  
			},this);
		   
		   this.dataGrid.on('cellclick',function(grid, cell, columnIndex, record , node , rowIndex , evt){
				  var column = grid.getHeaderCt().getHeaderAtIndex(columnIndex).colid;
		
				  if(record.get('system'))
					  return;
				  
				  switch(column){
				  	case 'editcolumn' : 
					  	if(!app.crud.orm.canEdit){
				  			return;
				  		}
					  	this.showEditField(record.get('name'));	
				  		break;
				  	case 'deleteindex':
				  		if(!app.crud.orm.canDelete){
				  			return;
				  		}			  		
				  		this.deleteField(record.get('name'));
				  		break;
				  	case 'link_type':
				  		if(!app.crud.orm.canEdit){
				  			return;
				  		}
				  		this.fireEvent('showdictionarywin',record.get('object'));
				  		break;
				  }
				  
			},this);
	   }
	   	   
	   this.configForm = Ext.create('Ext.form.Panel',{
		   bodyPadding:3,
		   frame:false,
		   title:appLang.CONFIG,
		   bodyCls:'formBody',
		   bodyBorder:false,
		   border:false,
		   fieldDefaults: {
	           labelWidth: 140,
	           labelAlign:'right',
	           width:300
	       },
		   items:[
		          {
		        	  xtype:'checkbox',
		        	  name:'rev_control',
		        	  fieldLabel:appLang.VC,
		        	  value:0
		          },{
		        	  xtype:'checkbox',
		        	  name:'save_history',
		        	  fieldLabel:appLang.HISTORY_LOG,
		        	  value:0
		          },{
		        	  xtype:'textfield',
		        	  name:'name',
		        	  fieldLabel:appLang.OBJECT_NAME,
		        	  allowBlank:false,
		        	  vtype:'alphanum'
		          },{
		        	  xtype:'textfield',
		        	  name:'title',
		        	  fieldLabel:appLang.TITLE,
		        	  allowBlank:false
		          },{
		        	  xtype:'textfield',
		        	  name:'table',
		        	  fieldLabel:appLang.TABLE_NAME,
		        	  allowBlank:false,
		        	  vtype:'alpha'
		          },{
		        	  xtype:'combobox',
		        	  name:'engine',
		        	  fieldLabel:appLang.TABLE_ENGINE,
		        	  displayField:'title',
		        	  valueField:'title',
		        	  queryMode:'local',
		        	  store:Ext.create('Ext.data.Store', {
		        		  model:'app.comboStringModel',
		        		  data:[
		        		        {id:'mysql' , title:"MyISAM"},
		        		        {id:'innodb' ,title:"InnoDB"},
		        		        {id:'memory' ,title:"Memory"}
		        		  ]
		        	  }),
		        	  allowBlank:false,
		        	  listeners:{
		        		  'change':{
		        			  fn:this.chackFieldsValidation,
		        			  scope:this
		        		  }
		        	  }
		          },{
		        	  xtype:'combobox',
		        	  name:'link_title',
		        	  fieldLabel:appLang.MSG_FIELD_USED_AS_TITLE,
		        	  store:this.dataStore,
		        	  displayField:'title',
		        	  valueField:'name',
		        	  allowBlank:true
		          },{
		        	  xtype:'fieldcontainer',
		        	  fieldLabel:' ',
		        	  labelSeparator:'',
		        	  items:mainConfButtons
		          }
		   ]
	   });
	   
	   this.tabPanel = Ext.create('Ext.tab.Panel',{
		   deferredRender:true,
		   items:[this.configForm]
	   });
	   
	   /*
	    * Add Fields tab if object exists
	    * and load fields store
	    */
	   if(this.objectName){
		   this.tabPanel.add(this.dataGrid);
		   this.tabPanel.setActiveTab(1);
		   this.tabPanel.add(this.indexGrid);
		   this.dataStore.load();
		   this.indexStore.load();
	   }
	   
	   this.items = [this.tabPanel];
		
	   this.callParent(arguments);
		
	   this.addEvents(
            /**
             * @event dataSaved
             */
           'dataSaved',
           'showdictionarywin'
       );  
	   
	   if(this.objectName){
			var handle = this;
			this.on('show' , function(){				
				var params = Ext.apply({object:this.objectName});				
				this.configForm.getForm().load({
					url:app.crud.orm.Actions.loadObjCfg,
					params:params,
					waitMsg:appLang.LOADING,
					success: function(form, action){	
		   		 		if(!action.result.success){
		   		 			Ext.Msg.alert(appLang.MESSAGE, action.result.msg);
		   		 		}	
		   	        },
		   	        failure: app.formFailure
				});				
			},this);
		}
	},
	chackFieldsValidation:function(combo, newValue, oldValue){
		if (newValue != 'Memory'){
			return;
		}
		
		var flag = false;
		this.dataStore.each(function(rec){
			if (Ext.Array.indexOf(app.crud.orm.textTypes , rec.get('type'))!=-1||
				Ext.Array.indexOf(app.crud.orm.blobTypes , rec.get('type'))!=-1)
			{
				flag = true;
			}
		},this);
		
		if(!flag){
			this.indexStore.each(function(rec){
				if (rec.get('fulltext')){
					flag = true;
				}
			},this);
		}
		
		if(flag){
			Ext.Msg.alert(appLang.MESSAGE, appLang.MSG_INVALID_MEMORYTABLE_FIELD);
			combo.setValue(oldValue);
		}
	},
	saveMainCfg: function(){
		var handle = this;
		this.configForm.getForm().submit({
			clientValidation: true,
			waitMsg: appLang.SAVING,
			method:'post',
			url:app.crud.orm.Actions.saveObjCfg,
			params:{record_id:this.objectName},
			success: function(form, action) {	
   		 		if(!action.result.success){
   		 			Ext.Msg.alert(appLang.MESSAGE, action.result.msg);
   		 		} else{
   		 			handle.fireEvent('dataSaved');		 			
   		 			/*
   		 			 * Define onjectName property , load fields store, add Fields tab
   		 			 * if new object has been created
   		 			 */
   		 			if(!handle.objectName){
   		 				handle.objectName = handle.configForm.getForm().findField('name').getValue(); 
   		 				handle.dataStore.proxy.extraParams.object = handle.objectName;  		 				
   		 				handle.tabPanel.add(handle.dataGrid);
   		 				handle.tabPanel.add(handle.indexGrid);
   		 				handle.dataStore.load();
   		 				handle.indexStore.load();
   		 				handle.setTitle(appLang.EDIT_OBJECT + ' &laquo;' + handle.objectName + '&raquo; ')
   		 			}
   		 		}
   	        },
   	        failure: app.formFailure
   	    });
	},
	/**
	 * Send delete index request
	 * @param string name
	 */
	deleteIndex:function(name){
		var handle = this;
		Ext.Msg.confirm(appLang.CONFIRM, appLang.MSG_CONFIRM_DELETE +' "'+name+'"?', function(btn){
			if(btn != 'yes'){
				return;
			}
			Ext.Ajax.request({
			 		url: app.crud.orm.Actions.deleteIndex,
			 		method: 'post',
			 		params:{
			 			'object':this.objectName,
			 			'name':name
			 		},
			         success: function(response, request) {
			 			response =  Ext.JSON.decode(response.responseText);
			 			if(response.success){
			 				handle.indexStore.load();
			 			}else{
			 				Ext.Msg.alert(appLang.MESSAGE, response.msg);
			 			}	
			       },
			       failure:app.formFailure
			 });
		},this);
	},
	/**
	 * Send delete field request
	 * @param string name
	 */
	deleteField:function(name){
		var handle = this;
		Ext.Msg.confirm(appLang.CONFIRM, appLang.MSG_CONFIRM_DELETE +' "'+name+'"?', function(btn){
			if(btn != 'yes'){
				return;
			}
			Ext.Ajax.request({
			 		url: app.crud.orm.Actions.deleteField,
			 		method: 'post',
			 		params:{
			 			'object':this.objectName,
			 			'name':name
			 		},
			         success: function(response, request) {
			 			response =  Ext.JSON.decode(response.responseText);
			 			if(response.success){
			 				handle.dataStore.load();
			 			}else{
			 				Ext.Msg.alert(appLang.MESSAGE , response.msg);
			 			}	
			       },
			       failure:app.formFailure
			 });
		},this);
	},
	showEditField:function(id){
		var win = Ext.create('app.crud.orm.FieldWindow',{
			objectName:this.objectName,
			fieldName:id,
			title:appLang.EDIT_FIELD,
			objectList:this.objectList,
			dictionaryUrl:app.crud.orm.Actions.dictionary
		});
		
		win.setTableEngine(this.configForm.getForm().findField('engine').getValue());
		
		win.on('dataSaved',function(){
			this.dataStore.load();
			this.indexStore.load();
			this.fireEvent('dataSaved');
		},this);
		
		win.show();
	},
	showEditIndex:function(index){
		
		var cols = [];
		
		this.dataStore.each(function(rec){
			cols.push(rec.get('name'));
		},this);
	
		var win = Ext.create('app.crud.orm.IndexWindow',{
			objectName:this.objectName,
			indexName:index,
			columnsList:cols,
			title:appLang.EDIT_INDEX
		});
		
		win.setTableEngine(this.configForm.getForm().findField('engine').getValue());
		
		win.on('dataSaved',function(){
			this.indexStore.load();
			this.fireEvent('dataSaved');
		},this);
		
		win.show();
	}
});